#include <pthread.h>
#include <iostream>
#include <unistd.h>

/*
 * 与互斥锁不同，条件变量是用来等待而不是用来上锁的。
 * 条件变量用来自动阻塞一个线程，直到某特殊情况发生为止。
 *
 * 通常条件变量和互斥锁同时使用。
 */

using namespace std;

pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
unsigned count = 0;

void* TakePhotoTaskProcess(void* arg)
{
    while (1) {
        pthread_mutex_lock(&count_lock);
        while (count == 0) {
            pthread_cond_wait(&count_nonzero, &count_lock);
        }

        printf("take photo successfuly.\n");
        count--;

        pthread_mutex_unlock(&count_lock);
    }

	return NULL;
}

int takephoto(void)
{
    printf("take photo\n");
    pthread_mutex_lock(&count_lock);
    if (count == 0)
        pthread_cond_signal(&count_nonzero);
	count++;
	pthread_mutex_unlock(&count_lock);

    return 0;
}

void* TakePhotoTask(void* arg)
{
    while (1) {
        takephoto();
        sleep(1);
    }

	return NULL;
}

int main()
{
	pthread_t tid1, tid2;

	pthread_mutex_init(&count_lock, NULL);
	pthread_cond_init(&count_nonzero, NULL);

	pthread_create(&tid1, NULL, TakePhotoTaskProcess, NULL);
	sleep(2);

	pthread_create(&tid2, NULL, TakePhotoTask, NULL);
	sleep(2);

	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);

	pthread_mutex_destroy(&count_lock);
	pthread_cond_destroy(&count_nonzero);

	cout << "ok!" << endl;
}

/*
 * g++ -o cond cond.cpp -lpthread
 */